package personal.leil.learning.bfs;

import personal.leil.learning.TreeNode;

import java.util.LinkedList;
import java.util.Queue;

/**
 * 计算二叉树的宽度
 * Created by Leil on 18.1.24
 */
public class CalcBinaryTreeWidth {


    /**
     * 在队列中添加标记点
     *
     * @param root 二叉树根节点
     * @return width of binary tree
     */
    public static int process1(TreeNode root) {
        if (root == null) {
            return 0;
        }
        Queue<TreeNode> queue = new LinkedList<>();
        queue.offer(root);
        queue.offer(null);
        int max = 1;
        while (!queue.isEmpty()) {
            TreeNode current = queue.poll();
            if (current == null) {
                System.out.println("queue size:" + queue.size());
                max = Math.max(max, queue.size());
                if (!queue.isEmpty()) {
                    queue.offer(null);
                }
                System.out.println();
                System.out.println("==============");
            } else {
                System.out.print(current.value + "  ");
                if (current.left != null) {
                    queue.offer(current.left);
                }
                if (current.right != null) {
                    queue.offer(current.right);
                }
            }
        }
        return max;
    }


    public static int process2(TreeNode root) {
        if (root == null) {
            return 0;
        }
        Queue<TreeNode> queue = new LinkedList<>();
        queue.offer(root);
        int max = 1;
        while (!queue.isEmpty()) {
            int sizeOfCurrentLevel = queue.size();
            max = Math.max(max, sizeOfCurrentLevel);
            for (int i = 0; i < sizeOfCurrentLevel; i++) {
                TreeNode current = queue.poll();
                System.out.print(current.value + "  ");
                if (current.left != null) {
                    queue.offer(current.left);
                }
                if (current.right != null) {
                    queue.offer(current.right);
                }
            }
            System.out.println();
        }
        return max;
    }


    /********************* For Test *************************/

    public static void main(String[] args) {
        // 构建一个二叉树
        TreeNode root = new TreeNode(1);
        root.left = new TreeNode(2);
        root.right = new TreeNode(3);
        root.left.left = new TreeNode(4);
        root.left.right = new TreeNode(5);
        root.right.left = new TreeNode(6);
        root.right.right = new TreeNode(7);
        root.left.left.right = new TreeNode(8);
        root.left.right.left = new TreeNode(9);


        // 进行广度优先遍历
        System.out.println("广度优先遍历结果：");
        int max = process1(root);
        System.out.println("width of binary tree: " + max);
    }


}
